package com.hb.android.autoreboot;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity测试";

    public static Button testButton;
    public static EditText testNumberEdit;
    public static EditText testIntervalEdit;

    private static int testTotalNumber = 5000;  // 循环测试总次数，默认1次
    private static int testIntervalTime = 10;  // 重启的间隔，默认10秒

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        testButton = findViewById(R.id.testButton);
        testNumberEdit = findViewById(R.id.testTime);
        testIntervalEdit = findViewById(R.id.testInterval);

        testButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mNumber;
                String mTime;
                mNumber = testNumberEdit.getText().toString().trim();
                mTime = testIntervalEdit.getText().toString().trim();
                // 默认循环1次
                if (mNumber.equals("")) {
                    mNumber = "5000";
                    Toast.makeText(MainActivity.this, "未设置次数，已默认设置为5000次", Toast.LENGTH_LONG).show();
                }
                if (mTime.equals("")) {
                    mTime = "10";
                    Toast.makeText(MainActivity.this, "未设置间隔，已默认设置为10秒", Toast.LENGTH_LONG).show();
                }
                try {
                    testTotalNumber = Integer.parseInt(mNumber);
                    testIntervalTime = Integer.parseInt(mTime);
                } catch (Exception e) {
                    e.printStackTrace();
                    testNumberEdit.setText("");
                    testTotalNumber = 5000;
                    testIntervalTime = 10;
                    Toast.makeText(MainActivity.this, "次数或间隔太大！已重置为默认值", Toast.LENGTH_LONG).show();
                    testNumberEdit.setText("");
                    testIntervalEdit.setText("");
                    return;
                }
                if (testTotalNumber < 1) {
                    testTotalNumber = 5000;
                    Toast.makeText(MainActivity.this, "最少循环1次！默认已设置为5000次", Toast.LENGTH_LONG).show();
                    testNumberEdit.setText("");
                    return;
                }
                if (testIntervalTime < 5) {
                    testIntervalTime = 10;
                    Toast.makeText(MainActivity.this, "最少间隔5秒！默认已设置为10秒", Toast.LENGTH_LONG).show();
                    testIntervalEdit.setText("");
                    return;
                }
                if (testTotalNumber > 10000) {
                    testTotalNumber = 5000;
                    Toast.makeText(MainActivity.this, "次数太大，最大循环 10000 次，请重新设置", Toast.LENGTH_LONG).show();
                    testNumberEdit.setText("");
                    return;
                }
                if (testIntervalTime > 120) {
                    testIntervalTime = 10;
                    Toast.makeText(MainActivity.this, "间隔太大，最大间隔 120 秒，请重新设置", Toast.LENGTH_LONG).show();
                    testIntervalEdit.setText("");
                    return;
                }

                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("开始测试？")
                        .setMessage("系统将在 " + testIntervalTime + " 秒后重启，重启开机之后隔 " + testIntervalTime + " 秒再次重启，这样循环 " + testTotalNumber + " 次。\n若要中途退出测试，请重新打开app按返回键退出！")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startTest();
                                testButton.setEnabled(false);
                                testNumberEdit.setEnabled(false);
                                testIntervalEdit.setEnabled(false);
                                Utils.logW(MainActivity.this, TAG, new Date() + "：开始测试 ！");
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });

        showLastTestResultDialog();
    }

    private void showLastTestResultDialog() {
        SharedPreferences sharedPreferences = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE);
        if (sharedPreferences == null) {
            return;
        }
        String lr = sharedPreferences.getString("lastResult", "");
        boolean isShow = sharedPreferences.getBoolean("isShowLastResult", false);
        boolean isTestIng = sharedPreferences.getBoolean("isTestIng", false);
        if (!lr.isEmpty() && isShow && !isTestIng) {
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle(lr)
                    .setPositiveButton("好的", null).create();
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    SharedPreferences.Editor editor = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE).edit();
                    editor.putBoolean("isShowLastResult", false);
                    editor.apply();
                }
            });
            alertDialog.show();
        }
    }

    /**
     * 开启测试
     */
    public void startTest() {
        SharedPreferences.Editor editor = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE).edit();
        editor.putString("lastResult", "最后一次测试结果：总循环次数:" + testTotalNumber + " 次，已成功完成:0次");
        editor.putBoolean("isShowLastResult", true);
        editor.putBoolean("isTestIng", true);
        editor.putInt("currentNumber", 0);
        editor.putInt("testTotalNumber", testTotalNumber);
        editor.putInt("testIntervalTime", testIntervalTime);
        editor.apply();

        Intent i = new Intent(this, RebootService.class);
        startService(i);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE);
        if (sharedPreferences == null) {
            return;
        }
        boolean isTestIng = sharedPreferences.getBoolean("isTestIng", false);
        int currentNumber = sharedPreferences.getInt("currentNumber", 0);
        int totalNumber = sharedPreferences.getInt("testTotalNumber", 1);
        int intervalTime = sharedPreferences.getInt("testIntervalTime", 10);
        String tips = "当前已完成重启次数:" + currentNumber + "  /  总次数:" + totalNumber;
        if (isTestIng) {
            try {
                testNumberEdit.setText(String.valueOf(totalNumber));
                testIntervalEdit.setText(String.valueOf(intervalTime));
                getSupportActionBar().setTitle(tips);
            } catch (Exception e) {
                e.printStackTrace();
            }
            testButton.setEnabled(false);
            testNumberEdit.setEnabled(false);
            testIntervalEdit.setEnabled(false);
        } else {
            testButton.setEnabled(true);
            testNumberEdit.setEnabled(true);
            testIntervalEdit.setEnabled(true);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        SharedPreferences sharedPreferences = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE);
        if (sharedPreferences == null) {
            return false;
        }
        int currentNumber = sharedPreferences.getInt("currentNumber", 0);
        boolean isTestIng = sharedPreferences.getBoolean("isTestIng", false);
        if (isTestIng) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                new AlertDialog.Builder(this)
                        .setTitle("是否确定退出测试？")
                        .setPositiveButton("确认退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SharedPreferences.Editor editor = getSharedPreferences("lastTestResult", Context.MODE_PRIVATE).edit();
                                editor.putBoolean("isShowLastResult", true);
                                editor.putBoolean("isTestIng", false);
                                editor.apply();
                                testButton.setEnabled(true);
                                testNumberEdit.setEnabled(true);
                                testIntervalEdit.setEnabled(true);
                                new AlertDialog.Builder(MainActivity.this)
                                        .setTitle("退出测试，测试已成功完成:" + currentNumber + "次，总次数:" + testTotalNumber)
                                        .setPositiveButton("确认", null)
                                        .show();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
                return true;
            }
            if (keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MENU) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
